<?php
class Modules extends CI_Model {
	
	private $firstParent = false;
	
	function __construct(){
		parent::__construct();
	}
	
	public function getMenu($params = array()){
		if($this->firstParent ===  false)
			$this->firstParent = $params['parentMenu'];
		$sql = "SELECT * FROM modules WHERE parent = {$params['parentMenu']} AND menu_group ='".$params['menuGroup']."'";
		$record = $this->db->query($sql)->result();
		$result = "";
		$menuGroup = $params['menuGroup'];
		
		if(count($record)>0){
			$controller = $this->router->fetch_class();
			$view = $this->router->fetch_method();
			$baseUrl = base_url();
			foreach($record as $key => $val){
				$classFNiv = "";
				if($val->parent == $this->firstParent)
					$classFNiv = "fNiv";
// 				$link = $val->link;
// 				$controllerMenu = preg_split('/\//',$link);
				if($controller.'/'.$view == $val->link)
					$result .= "<li class='current'>\n";
				else
					$result .= "<li>\n";
				$link = '';
				if($val->link != '#')
				$link = "href = '".base_url().$val->link."'";
				if($this->checkChild($val->id, $menuGroup)){
					
					$result .= "<a {$link} class='parent {$classFNiv}'>";
					$result .= $val->name;
					$result .= "</a>\n";
					
					$result .= "<ul>\n";
					
					if($classFNiv!="")
						$result .="<li class='arrow'></li>";
					$params['parentMenu'] = $val->id;
					$result .= $this->getMenu($params);
					
					$result .= "</ul>\n";
					
				}else{
					$result .= "<a {$link} class='{$classFNiv}'>";
					$result .= $val->name;
					$result .= "</a>\n";
				}
				$result .= "</li>\n";
			}
		}
		return $result;
	}
	
	private function checkChild($parent, $menuGroup){
		$sql = "SELECT * FROM modules WHERE parent = {$parent} AND menu_group ='".$menuGroup."'";
		$record = $this->db->query($sql)->result();
		if(count($record)>0)
			return true;
		else
			return false;
	}
	
	
}